
var express = require("express");
var app = express();
const router = require('./router/index')
app.use(express.urlencoded({extended: false}))
app.use(express.static('public'))
const expressJWT = require("express-jwt")
const moment = require('moment');
// 跨域
const cors = require('cors');
app.use(cors())

const secretKey = 'no1'

let ws = require('nodejs-websocket');
console.log("開始建立連接...");

let users = [], conns = {};

function boardcast(obj) {
    // bridge 用來實現一對一的主要參數
    if (obj.bridge && obj.bridge.length) {
        obj.bridge.forEach(item => {
            conns[''+item+''] && conns[''+item+''].sendText(JSON.stringify(obj));
        });
        return;
    }
    server.connections.forEach((conn, index) => {
        conn.sendText(JSON.stringify(obj));
    })
}

let server = ws.createServer(function(conn) {
    conn.on("text", function(obj) {
        console.log("message:"+obj)
        obj = JSON.parse(obj);
        // 將所有uid對應的連接conn存到一個對象
        conns[''+obj.uid+''] = conn;
        if (obj.type === 1) {
            let isuser = users.some(item => {
                return item.uid = obj.uid
            })
            if (!isuser) {
                users.push({
                    nickname: obj.nickname,
                    uid: obj.uid
                });
            }
            boardcast({
                type: 1,
                date: moment().format('YYYY-MM-DD HH:mm:ss'),
                msg:obj.nickname+'加入聊天室',
                users: users,
                uid: obj.uid,
                nickname: obj.nickname,
                // 增加參數
                bridge: obj.bridge
            })
        } else {
            boardcast({
                type: 2,
                date: moment().format('YYYY-MM-DD HH:mm:ss'),
                msg:obj.msg,
                uid: obj.uid,
                nickname: obj.nickname,
                // 增加參數
                bridge: obj.bridge
            })

            

        }
        // conn.sendText("My name is Web Alice!");
    })
    conn.on("close", function(code, reason) {
        console.log("關閉連接")
    })
    conn.on("error", function(code, reason) {
        console.log("異常關閉")
    })
}).listen(8001)
console.log("WebSocket建立完畢")

express().get('/', (req, res) => {
    throw new Error('服務器內部發生了錯誤！')
    res.send('Home page.')
});
// 註冊路由模塊，添加訪問前綴
app.use(
    expressJWT.expressjwt({secret: secretKey, algorithms: ["HS256"]}).unless({
        path: [
            '/',
            '/hello',
            '/api/sign/login',
            '/api/sign/register',
            '/api/sign/resetPwd'
        ]
    })
)
app.use('/api', router)


app.use((err,req,res,next) => {
    if(err.name == 'UnauthorizedError') {
        return res.send({status: -1, msg: '身份認證失敗,請重新登錄'})
    }
})


// function select() {
//     pool.getConnection((err, connection) => {
//         if (err) throw err;
//         let sql = "select * from goods";
//         connection.query(sql, (errors, results, fields) => {
//             connection.release();
//             if (errors) throw errors;
//             console.log(results);
//         })
//     })
// }

// select();

//监听8080端口
app.listen(80, () => {
    console.log('express server running at http://127.0.0.1')
  })
